<?php

namespace backend\services\mall\special;

use Yii;
use yii\helpers\Json;
use backend\extensions\ApiBaseService;
use backend\models\mall\special\MallSpecial;
use backend\models\mall\special\MallSpecialFloor;
use backend\models\mall\special\MallSpecialFloorGoods;
use common\tools\Util;

/**
 * 专题
 */
class MallSpecialService extends ApiBaseService
{
    /**
     * 列表过滤条件
     * @param array $params 参数 
     * @return \yii\db\Query
     * **/
    public static function getListQuery($params)
    {
        $query = MallSpecial::find();
        MallSpecial::setQuery($query, $params);
        return $query;
    }

    /**
     * 列表
     * @param array $params 参数
     * @return array
     * **/
    public static function getList($params)
    {
        $query = self::getListQuery($params);
        $total = intval($query->count());

        list($offset, $limit) = \common\tools\Util::getLimit($params['page'] ?? 1, $params['page_size'] ?? 20);
        $query->offset($offset)->limit($limit);
        // echo $query->createCommand()->getRawSql();
        $list = $query->orderBy(['id' => SORT_DESC])->asArray()->all();

        foreach ($list as &$value) {
            $value['state_name'] = MallSpecial::$state[$value['state']] ?? '';
            $value['is_home_name'] = MallSpecial::$is_home[$value['is_home']] ?? '';
            $value['link'] = '/pages-mall/special/index?code=' . $value['code'];
        }

        return [
            'total' => $total,
            'list' => $list
        ];
    }

    /**
     * 详情
     * @param array $params 参数 
     * **/
    public static function detail($params)
    {
        $condition = ['id' => $params['id']];
        $info = MallSpecial::getDataOne($condition);
        $info['floor'] = MallSpecialFloor::getAll(['special' => $params['id']]) ?? [];
        if(!empty($info['floor'])) {
            foreach($info['floor'] as $key=> $item) {
                $ids= MallSpecialFloorGoods::getIndexAll('gid',['special_floor'=> $item['id']], 'gid');
                $ids = array_keys($ids);
                $info['floor'][$key]['goods_ids']  = implode(',', $ids);
            }
        } 
        if ($info) {
            $info['banner'] = Json::decode($info['banner'], true);
        }
        return $info;
    }

    /**
     * 新增
     * @param array $params 参数 
     * **/
    public static function create($params)
    {
        $is_home = $params['is_home'] ?? MallSpecial::IS_HOME_NO;
        if ($is_home == MallSpecial::IS_HOME_YES) {
            $home_special = MallSpecial::find()->where(['is_home' => MallSpecial::IS_HOME_YES])->one();
            if ($home_special) {
                return self::jsonError('首页专题只能设置一个');
            }
        }

        $time = date('Y-m-d H:i:s');
        $params['create_time'] = $time;
        $params['update_time'] = $time;
        // 轮播图
        $banenr_data = $params['banner'] ?: [];
        $params['banner'] = Json::encode($banenr_data);
        $params['code'] = Util::createUniqueId();

        $floor_data = $params['floor'];
        unset($params['floor']);
        // 保存数据——专题数据——楼层数据——商品数据
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            $special_id =  MallSpecial::create($params);
            foreach ($floor_data as $key => $item) {
                $sp_data = [
                    'special' => $special_id,
                    'name' => $item['name'],
                    'state' => $item['state'],
                    'sort' => empty($item['sort']) ? 0 : $item['sort']
                ];
                // 保存楼层
                $sf_id = MallSpecialFloor::create($sp_data);

                if (isset($item['goods_ids']) && !empty($item['goods_ids'])) {
                    $rows = [];
                    $barcodesArr = array_unique(explode(',', $item['goods_ids']));
                    foreach ($barcodesArr as $bItem) {
                        $rows[] = [
                            'special_floor' => $sf_id,
                            'gid' => $bItem,
                            'special' => $special_id,
                        ];
                    }
                    // 保存商品
                    \Yii::$app->db->createCommand()->batchInsert(MallSpecialFloorGoods::tableName(), array_keys($rows[0]), $rows)->execute();
                }
            }

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 更新
     * @param array $params 参数 
     * **/
    public static function update($params)
    {
        $id = $params['id'];
        $is_home = $params['is_home'] ?? MallSpecial::IS_HOME_NO;
        if ($is_home == MallSpecial::IS_HOME_YES) {
            $home_special = MallSpecial::find()
                ->where(['is_home' => MallSpecial::IS_HOME_YES])
                ->andWhere(['!=', 'id', $id])->one();
            if ($home_special) {
                return self::jsonError('首页专题只能设置一个');
            }
        }
        $params['update_time'] = date('Y-m-d H:i:s');
        // 轮播图
        $banenr_data = $params['banner'] ?: [];
        $special_data = [
            'banner' => Json::encode($banenr_data),
            'name' => $params['name'],
            'bg_color' => $params['bg_color'],
            'state' => $params['state'],
            'is_home' => $params['is_home'],
            'act_color' => $params['act_color'],
            'txt_color' => $params['txt_color'],
            'update_time' => $params['update_time']
        ];

        $floor_data = $params['floor'];
        unset($params['floor']);
        // 保存数据——专题数据——楼层数据——商品数据
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            MallSpecial::updateData($special_data, ['id'=>$id]);
            MallSpecialFloor::deleteAll(['special' => $id]);
            MallSpecialFloorGoods::deleteAll(['special' => $id]);

            foreach ($floor_data as $key => $item) {
                $sp_data = [
                    'special' => $id,
                    'name' => $item['name'],
                    'state' => $item['state'],
                    'sort' => empty($item['sort']) ? 0 : $item['sort']
                ];
                // 保存楼层
                $sf_id = MallSpecialFloor::create($sp_data);

                if (isset($item['goods_ids']) && !empty($item['goods_ids'])) {
                    $rows = [];
                    $barcodesArr = array_unique(explode(',', $item['goods_ids']));
                    foreach ($barcodesArr as $bItem) {
                        $rows[] = [
                            'special_floor' => $sf_id,
                            'gid' => $bItem,
                            'special' => $id,
                        ];
                    }
                    // 保存商品
                    \Yii::$app->db->createCommand()->batchInsert(MallSpecialFloorGoods::tableName(), array_keys($rows[0]), $rows)->execute();
                }
            }

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 删除
     * @param array $params 参数 
     * **/
    public static function delete($params)
    {
        $id = $params['id'];
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            MallSpecial::del(['id'=>$id]);
            MallSpecialFloor::deleteAll(['special' => $id]);
            MallSpecialFloorGoods::deleteAll(['special' => $id]);

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }
}
